package com.young.jdbc.myjdbc;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @Author: young
 * @Date: 2021-12-03 9:53
 * @Description: JdbcUtils工具类的封装
 */
public class JdbcUtils {
 private static String user;
 private static String password;
 private static String url;
 private static String driver;

 // 在static代码块中初始化
 static {
  try {
   Properties properties = new Properties();
   properties.load(new FileInputStream("src\\mysql.properties"));
   user = properties.getProperty("user");
   password = properties.getProperty("password");
   url = properties.getProperty("url");
   driver = properties.getProperty("driver");
   Class.forName(driver);
  } catch (IOException | ClassNotFoundException e) {
   // 在实际开发中，可以这样处理
   // 将编译异常转成运行异常；调用者可以捕获该异常，也可以默认处理该异常，比较方便
   throw new RuntimeException(e);
  }
 }
 // 连接数据库，返回Connection
 public static Connection getConnection(){
  try {
   return DriverManager.getConnection(url,user,password);
  } catch (SQLException e) {
   throw new RuntimeException(e);
  }
 }
 // 关闭资源
 public static void close(ResultSet set, Statement statement,Connection connection){
  try {
   if (set != null){
    set.close();
   }
   if (statement != null){
    statement.close();
   }
   if (connection != null){
    connection.close();
   }
  }catch (SQLException e){
   throw new RuntimeException(e);
  }
 }
}
